package com.green.voluntaryfiling.controller;

import com.green.voluntaryfiling.common.DataGridView;
import com.green.voluntaryfiling.common.ResultObj;
import com.green.voluntaryfiling.service.UniversityInfoService;
import com.green.voluntaryfiling.service.UniversityScoreByMajorService;
import com.green.voluntaryfiling.vo.MatchInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.green.voluntaryfiling.common.ResultObj.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Green
 * @Date: 2022/03/18/0:23
 * @Description:
 */
@RequestMapping("school")

@RestController
public class SchoolController {

    //重复标志
    private static String province_flag = null;
    private static Double score_flag = null;
    private static Integer ranking_flag = null;
    private static String subject_flag = null;
    private static Integer page_flag = null;


    @Autowired
    private UniversityInfoService universityInfoService;
    @Autowired
    private UniversityScoreByMajorService universityScoreByMajorService;

    @Autowired
    RedisTemplate redisTemplate;//redis缓存

    /**
     * 查询学校信息
     *
     * @param schoolMsg
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("searchSchoolInfo")
    public ResultObj searchSchoolInfo(String schoolMsg, int page, int limit) {
        DataGridView dataGridViewSI = null;
        try {
            ValueOperations<String, Object> schoolCache = redisTemplate.opsForValue();
            String target = schoolMsg+"&&"+page+"&&"+limit;
            //判断是否缓存击中
            dataGridViewSI = (DataGridView) schoolCache.get(target);

            if (dataGridViewSI != null) {
                if (StringUtils.isBlank(schoolMsg)) {
                    return new ResultObj(UNIVERSITY_INFO_SUCCESS_CODE, "查询学校信息成功（全部学校）", dataGridViewSI);
                } else {
                    return new ResultObj(UNIVERSITY_INFO_SUCCESS_CODE, "查询学校信息成功（部分匹配学校）", dataGridViewSI);
                }
            } else {
                //没有缓存击中，从数据库查询数据，并将其存于redis缓存
                if (StringUtils.isBlank(schoolMsg)) {    //空字符串查询全部信息并返回
                    dataGridViewSI = universityInfoService.queryAllUniversityInfo(page, limit);
                    schoolCache.set(target, dataGridViewSI);
                    return new ResultObj(UNIVERSITY_INFO_SUCCESS_CODE, "查询学校信息成功（全部学校）", dataGridViewSI);

                } else {                                  //模糊匹配查询学校信息返回
                    dataGridViewSI = universityInfoService.queryLikeUniversityInfo(schoolMsg, page, limit);
                    schoolCache.set(target, dataGridViewSI);
                    return new ResultObj(UNIVERSITY_INFO_SUCCESS_CODE, "查询学校信息成功（部分匹配学校）", dataGridViewSI);
                }
            }

        } catch (Exception e) {
            return ResultObj.UNIVERSITY_INFO_ERROR;
        }
    }//end Resultobj searchSchoolInfo()


    /**
     * 匹配院校信息
     *
     * @param matchInfoVo
     * @return
     */
    @RequestMapping("matchschoolList")
    public ResultObj matchschoolList(MatchInfoVo matchInfoVo) {
        try {

            /*
            * 缓存命中区
            * */

            ValueOperations<String, Object> matchSchoolCache = redisTemplate.opsForValue();
            DataGridView dataGridViewML = null;
            //KEY
            String matchStr = matchInfoVo.getProviceValue()+""+matchInfoVo.getSubject()
                    +""+matchInfoVo.getSt_score()+""+matchInfoVo.getSt_ranking()+""+matchInfoVo.getUsername();

            if (matchStr == null || matchStr.isEmpty()){
                return ResultObj.UNIVERSITY_MATCH_FAIL;
            }

            //判断命中缓存 null:未命中 !null:命中，但需要判断是否是有效数据
            dataGridViewML = (DataGridView) matchSchoolCache.get(matchStr);
            if (dataGridViewML != null){

                if (!dataGridViewML.getCount().equals(-1)){
                    return new ResultObj(UNIVERSITY_MATCH_SUCCESS, "智能匹配成功", dataGridViewML);
                }else {
                    return UNIVERSITY_MATCH_FAIL;
                }

            }else {

                /*
                * 缓存未命中区
                * */

                //临时性物理转==>理科 | 历史转==>文科操作
                if (matchInfoVo.getSubject().equalsIgnoreCase("历史")) {
                    matchInfoVo.setSubject("文科");
                } else {
                    matchInfoVo.setSubject("理科");
                }

                /*
                    == 比地址 , equals比内容
                    这个if循环真的情况一般用不到，重构后！！
                */
                if (province_flag != null && score_flag != null && subject_flag != null && ranking_flag != null &&
                        province_flag.equalsIgnoreCase(matchInfoVo.getProviceValue()) && subject_flag.equalsIgnoreCase(matchInfoVo.getSubject()) &&
                        score_flag.equals(matchInfoVo.getSt_score()) && ranking_flag.equals(matchInfoVo.getSt_ranking()) && !matchInfoVo.getPage().equals(1)) { //非第一次匹配并且没有更改过任何数据只是下拉刷新，仅一种情况
                    //page页面重复
                    if (page_flag.equals(matchInfoVo.getPage())) {

                        return new ResultObj(UNIVERSITY_MATCH_PAGE_ERROR, UNIVERSITY_MATCH_PAGE_ERROR_MSG);

                    } else {
                        //记录当前页面已被使用，累计确认
                        page_flag = matchInfoVo.getPage();
                        //直接返回数据
                        dataGridViewML = this.universityInfoService.matchSchoolWithSearchingSchoolFirst(matchInfoVo);
                        if (dataGridViewML.getCount() != 0) {
                            //比较危险的写法
                            return new ResultObj(UNIVERSITY_MATCH_SUCCESS, "智能匹配成功", dataGridViewML);
                        } else {//数据为空
                            return ResultObj.UNIVERSITY_MATCH_FAIL;
                        }
                    }

                } else {
                    //任何不是刷新的情况，包括但不限于第一次查询|标志位未赋值|4个标志位存在更改情况，需要重新进行匹配查询操作
                    //设置标志变量
                    province_flag = matchInfoVo.getProviceValue();
                    subject_flag = matchInfoVo.getSubject();
                    score_flag = matchInfoVo.getSt_score();
                    ranking_flag = matchInfoVo.getSt_ranking();
                    page_flag = matchInfoVo.getPage();

                    //学校、专业优先暂时忽略
                    dataGridViewML = this.universityInfoService.matchSchoolWithSearchingSchoolFirst(matchInfoVo);
                    if (dataGridViewML.getCount() == 0 || dataGridViewML == null) {//失败
                        matchSchoolCache.set(matchStr,new DataGridView(Long.valueOf(-1),null));
                        return ResultObj.UNIVERSITY_MATCH_FAIL;
                    }

                    //加入redisCache 没有缓存击中，从数据库查询数据，并将其存于redis缓存
                    matchSchoolCache.set(matchStr,dataGridViewML);
                    return new ResultObj(UNIVERSITY_MATCH_SUCCESS, "智能匹配成功", dataGridViewML);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UNIVERSITY_MATCH_ERROR;
        }
    }


    /**
     * 查询详细院校信息
     *
     * @param university_name
     * @param subject
     * @return
     */
    @RequestMapping("schoolDetail")
    public ResultObj schoolDetail(String university_name, String subject) {
        try {

            //临时性物理转==>理科 | 历史转==>文科操作
            if (subject.equalsIgnoreCase("历史")) {
                subject = "文科";
            } else {
                subject = "理科";
            }
            //redis 缓存
            ValueOperations<String, Object> schoolDetailCache = redisTemplate.opsForValue();
            DataGridView dataGridViewSD = null;
            String target = university_name + "schoolDetail" + subject;

            dataGridViewSD = (DataGridView) schoolDetailCache.get(target);

            if(dataGridViewSD != null){

                if (!dataGridViewSD.getCount().equals(-1)) {
                    return new ResultObj(UNIVERSITY_DETAIL_SUCCESS_CODE, UNIVERSITY_DETAIL_SUCCESS_MSG, dataGridViewSD);
                } else {
                    return UNIVERSITY_DETAIL_FAIL;
                }
            }else{
                dataGridViewSD = this.universityInfoService.querySchoolDetail(university_name, subject);

                if (dataGridViewSD != null) {
                    schoolDetailCache.set(target,dataGridViewSD);
                    return new ResultObj(UNIVERSITY_DETAIL_SUCCESS_CODE, UNIVERSITY_DETAIL_SUCCESS_MSG, dataGridViewSD);
                } else {
                    //失败
                    schoolDetailCache.set(target,new DataGridView(Long.valueOf(-1),null));
                    return UNIVERSITY_DETAIL_FAIL;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UNIVERSITY_DETAIL_FAIL;
        }
    }


    /**
     * 查询院校专业信息ALL
     *
     * @param university_name
     * @param subject
     * @return
     */
    @RequestMapping("majorDetail")
    public ResultObj majorDetail(String university_name, String subject) {
        try {

            //临时性物理转==>理科 | 历史转==>文科操作
            if (subject.equalsIgnoreCase("历史")) {
                subject = "文科";
            } else {
                subject = "理科";
            }
            ValueOperations<String, Object> majorDetailCache = redisTemplate.opsForValue();
            DataGridView dataGridViewMD = null;
            String target = university_name + "majorDetail" + subject;
            //判断是否缓存击中
            dataGridViewMD = (DataGridView) majorDetailCache.get(target);

            if (dataGridViewMD != null) {
                if (dataGridViewMD.getCount().equals(-1)) {
                    return UNIVERSITY_MAJOR_DETAIL_FAIL;
                } else {
                    return new ResultObj(UNIVERSITY_MAJOR_DETAIL_SUCCESS_CODE, UNIVERSITY_MAJOR_DETAIL_SUCCESS_MSG, dataGridViewMD);
                }

            }else {
                //没有缓存击中，从数据库查询数据，并将其存于redis缓存
                dataGridViewMD = this.universityScoreByMajorService.queryMajorWithName(university_name, subject);

                if (dataGridViewMD == null) {
                    //失败
                    majorDetailCache.set(target, new DataGridView(Long.valueOf(-1),null));
                    return UNIVERSITY_MAJOR_DETAIL_FAIL;
                } else {
                    majorDetailCache.set(target, dataGridViewMD);
                    return new ResultObj(UNIVERSITY_MAJOR_DETAIL_SUCCESS_CODE, UNIVERSITY_MAJOR_DETAIL_SUCCESS_MSG, dataGridViewMD);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            return UNIVERSITY_MAJOR_DETAIL_ERROR;
        }
    }


}
